Page({ 
  data: { 
    orderGoods: [], // 订单商品信息
    totalPrice: 0, // 订单总价
    selectedAddress: null, // 选中的收货地址
    addressList: [], // 收货地址列表
    couponText: '暂无可用优惠券',
    couponDiscount: 1,
    discountedPrice: 0
  },

  onShow() { 
    const coupon = wx.getStorageSync('selectedCoupon');
    // 确保 totalPrice 是数值类型
    const totalPrice = parseFloat(this.data.totalPrice) || 0;
    if (coupon && coupon.selected) { 
      this.setData({ 
        couponText: '8折',
        couponDiscount: 0.8,
        // 重新计算优惠后价格
        discountedPrice: (totalPrice * 0.8).toFixed(2)
      });
    } else { 
      wx.removeStorageSync('selectedCoupon');
      // 确保在未使用优惠券时，应付金额为商品原价
      this.setData({
        couponText: '暂无可用优惠券',
        couponDiscount: 1,
        discountedPrice: totalPrice.toFixed(2)
      });
    }
    // 每次显示页面时加载最新的地址列表和默认地址
    this.loadAddressList();
  },

  onLoad(options) {
    try {
      const orderInfo = JSON.parse(decodeURIComponent(options.orderInfo));
      // 确保 totalPrice 是数值类型
      const totalPrice = parseFloat(orderInfo.totalPrice) || 0;
      // 确保在加载时正确计算优惠后价格
      const discountedPrice = (totalPrice * this.data.couponDiscount).toFixed(2);
      this.setData({
        orderGoods: orderInfo.goodsList,
        totalPrice,
        discountedPrice
      });
    } catch (error) {
      console.error('解析订单信息时出错:', error);
      // 可以在这里添加默认值或者提示用户重新选择商品
    }
    this.loadAddressList();
  },

  // 加载收货地址列表
  loadAddressList() {
    const addressList = wx.getStorageSync('addressList') || [];
    const selectedAddress = addressList.find(item => item.isDefault);
    this.setData({
      addressList,
      selectedAddress
    });
  },

  // 选择收货地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/address/address?from=confirmOrder'
    });
  },

  // 新增收货地址
  addNewAddress() {
    wx.navigateTo({
      url: '/pages/address-edit/address-edit'
    });
  },

  // 选择优惠券
  selectCoupon() {
    wx.navigateTo({
      url: '/pages/Coupon/Coupon'
    });
  },

  // 模拟支付
  handlePayment() { 
    if (!this.data.selectedAddress) { 
      wx.navigateTo({ 
        url: '/pages/PayFail/PayFail' 
      }); 
      return; 
    } 

    // 获取当前订单编号，若不存在则从 001 开始
    let orderNumber = wx.getStorageSync('lastOrderNumber') || '000';
    orderNumber = String(Number(orderNumber) + 1).padStart(3, '0');
    wx.setStorageSync('lastOrderNumber', orderNumber);

    // 构造订单信息
    const orderInfo = { 
      orderNumber: orderNumber, // 添加订单编号
      goodsList: this.data.orderGoods,
      totalPrice: this.data.totalPrice,
      discountedPrice: this.data.discountedPrice,
      selectedAddress: this.data.selectedAddress,
      paymentMethod: '微信支付',
      orderStatus: '待支付',
      createTime: new Date().toLocaleString(),
      paymentInfo: { 
        totalAmount: this.data.totalPrice,
        discountAmount: this.data.totalPrice - this.data.discountedPrice,
        actualPayment: this.data.discountedPrice
      },
      receiverInfo: this.data.selectedAddress,
      logisticsInfo: { 
        status: '待发货', 
        trackingNumber: 'SF' + Math.floor(Math.random() * 1000000000), 
        trackingUrl: '' 
      }
    };

    // 清除本地存储的订单信息
    wx.removeStorageSync('unpaidOrderInfo');

    // 模拟支付结果，80% 成功率 
    const isSuccess = Math.random() > 0.2; 
    if (isSuccess) { 
      // 支付成功，更新订单状态为待发货 
      orderInfo.orderStatus = '待发货'; 
      // 获取已支付订单列表 
      const paidOrders = wx.getStorageSync('paidOrders') || []; 
      paidOrders.push(orderInfo); 
      wx.setStorageSync('paidOrders', paidOrders); 
      // 清除未支付订单信息 
      wx.removeStorageSync('unpaidOrderInfo'); 
      // 支付成功，跳转到支付成功页面并传递订单信息 
      wx.navigateTo({ 
        url: `/pages/PaySuccess/PaySuccess?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}` 
      }); 
    } else { 
      // 支付失败，跳转到支付失败页面并传递订单信息 
      wx.navigateTo({ 
        url: `/pages/PayFail/PayFail?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}` 
      }); 
    } 
  },

  onUnload() {
    // 获取当前订单编号，若不存在则从 001 开始
    let orderNumber = wx.getStorageSync('lastOrderNumber') || '000';
    orderNumber = String(Number(orderNumber) + 1).padStart(3, '0');
    wx.setStorageSync('lastOrderNumber', orderNumber);

    // 页面卸载时保存未支付的订单信息
    const orderInfo = { 
      orderNumber: orderNumber, // 添加订单编号
      goodsList: this.data.orderGoods,
      totalPrice: this.data.totalPrice,
      discountedPrice: this.data.discountedPrice,
      selectedAddress: this.data.selectedAddress,
      paymentMethod: '微信支付',
      orderStatus: '待支付',
      createTime: new Date().toLocaleString(),
      paymentInfo: { 
        totalAmount: this.data.totalPrice,
        discountAmount: this.data.totalPrice - this.data.discountedPrice,
        actualPayment: this.data.discountedPrice
      },
      receiverInfo: this.data.selectedAddress,
      logisticsInfo: { 
        status: '待发货', 
        trackingNumber: 'SF' + Math.floor(Math.random() * 1000000000), 
        trackingUrl: '' 
      }
    };
    wx.setStorageSync('unpaidOrderInfo', orderInfo);
  }
});